<template>
	<view>
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="数据分析汇总" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 标签页导航 -->
		<view class="tab-container">
			<view class="tab-item" v-for="(tab, index) in tabList" :key="index"
				:class="{ active: currentTab === index }" @tap="switchTab(index)">
				{{ tab.name }}
			</view>
		</view>

		<!-- 筛选表单 -->
		<view class="filter-container">
			<view class="filter-row">
				<view class="filter-item">
					<text class="label">监测年份</text>
					<view class="input-wrapper" @tap="openYearPicker">
						<input class="input" :value="getSelectedYearsText()" placeholder="选择年份" disabled />
						<u-icon name="calendar" size="20" color="#999"></u-icon>
					</view>
				</view>
				<view class="filter-item">
					<text class="label">监测树种</text>
					<view class="input-wrapper" @tap="showTreeMultiPicker = true">
						<input class="input" :value="getSelectedTreeTypesText()" placeholder="请选择树种" disabled />
						<u-icon name="arrow-down" size="16" color="#999"></u-icon>
					</view>
				</view>
			</view>

			<view class="filter-row">
				<view class="filter-item">
					<text class="label">监测类型</text>
					<view class="input-wrapper" @tap="showMonitorPicker = true">
						<input class="input" :value="filterData.monitorType" placeholder="请选择监测类型" disabled />
						<u-icon name="arrow-down" size="16" color="#999"></u-icon>
					</view>
				</view>
				<view class="filter-item">
					<text class="label">级别</text>
					<view class="input-wrapper" @tap="showLevelPicker = true">
						<input class="input" :value="filterData.level" placeholder="请选择级别" disabled />
						<u-icon name="arrow-down" size="16" color="#999"></u-icon>
					</view>
				</view>
			</view>

			<view class="filter-buttons">
				<button class="btn btn-query" @tap="queryData">查询</button>
				<button class="btn btn-reset" @tap="resetFilter">重置</button>
			</view>
		</view>

		<!-- 图表区域 -->
		<!-- 各市抽检数据分析 -->
		<view v-if="currentTab === 0" class="chart-container">
			<view class="chart-title">
				各市抽检数据分析
				<text v-if="selectedYears && selectedYears.length > 0" class="year-info">
					({{ getSelectedYearsText() }})
				</text>
			</view>
			<view class="chart-wrapper">
				<view class="city-group" v-for="(cityData, cityIndex) in getAllCitiesData()" :key="cityIndex">
					<view class="city-name">{{ cityData.name }}</view>
					<view class="year-bars">
						<view v-for="(yearData, yearIndex) in cityData.years" :key="yearIndex" class="year-bar-item">
							<view class="year-label">{{ yearData.year }}</view>
							<view class="chart-bar">
								<view class="bar-fill" :class="'bar-' + (yearIndex + 1)"
									:style="{ width: yearData.rate + '%' }"></view>
							</view>
							<text class="chart-value">{{ yearData.rate }}%</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 各树种抽检数据分析 -->
		<view v-if="currentTab === 1" class="chart-container">
			<view class="chart-title">各树种抽检数量及占比</view>
			<view class="chart-wrapper">
				<!-- 有数据时显示图表 -->
				<view v-if="hasRingData()" class="ring-item">
					<qiun-data-charts type="ring" :opts="ringOpts" :chartData="ringData" :canvas2d="true"
						canvasId="treeRingChart" />
				</view>
				<!-- 无数据时显示提示 -->
				<view v-else class="no-data-container">
					<view class="no-data-icon">📊</view>
					<view class="no-data-text">暂无数据</view>
					<view class="no-data-tip">请选择筛选条件后点击查询</view>
				</view>
			</view>
		</view>

		<!-- 抽检合格率分析 -->
		<view v-if="currentTab === 2" class="chart-container">
			<view class="chart-title">抽检合格率分析</view>
			<view class="chart-wrapper">
				<qiun-data-charts type="column" :opts="columnOpts" :chartData="getPassRateChartData()" :canvas2d="true"
					canvasId="passRateColumnChart" />
			</view>
		</view>

		<!-- 年份选择器 -->
		<u-picker :show="showYearPicker" :columns="yearColumns" :defaultValue="getCurrentYearDefault()" @confirm="yearConfirm" @cancel="showYearPicker = false"
			@close="showYearPicker = false" />

		<!-- 树种选择器 -->
		<u-picker :show="showTreePicker" :columns="treeColumns" @confirm="treeConfirm" @cancel="showTreePicker = false"
			@close="showTreePicker = false" />

		<!-- 对比类型选择器（已移除，监测树种直接使用树种选择器） -->

		<!-- 监测类型选择器 -->
		<u-picker :show="showMonitorPicker" :columns="monitorColumns" @confirm="monitorConfirm"
			@cancel="showMonitorPicker = false" @close="showMonitorPicker = false" />

		<!-- 级别选择器 -->
		<u-picker :show="showLevelPicker" :columns="levelColumns" @confirm="levelConfirm"
			@cancel="showLevelPicker = false" @close="showLevelPicker = false" />

		<!-- 自定义树种多选弹窗 -->
		<u-popup :show="showTreeMultiPicker" mode="bottom" @close="showTreeMultiPicker = false">
			<view class="tree-multi-picker">
				<view class="picker-header">
					<text class="picker-title">选择树种</text>
					<text class="picker-confirm" @tap="confirmTreeMultiSelect">确定</text>
				</view>
				<view class="picker-content">
					<view class="tree-item" v-for="(tree, index) in treeColumns[0]" :key="index" 
						@tap="toggleTreeSelect(tree)">
						<view class="tree-checkbox" :class="{ active: filterData.treeType.includes(tree) }">
							<u-icon v-if="filterData.treeType.includes(tree)" name="checkmark" size="16" color="#fff"></u-icon>
						</view>
						<text class="tree-label">{{ tree }}</text>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { getTreeSpecies, typeShujufenxi, levelShujufenxi, getTreeSpeciesList } from '@/api/shujufenxi'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			currentTab: 0,
			tabList: [
				{ name: '各市抽检数据分析' },
				{ name: '各树种抽检比例分析' },
				{ name: '各市抽检数据分析' }
			],
			filterData: {
				years: [], // 改为数组支持多选
				treeType: [], // 改为数组支持多选
				monitorType: '',
				level: ''
			},
			treeSpeciesData: [], // 存储完整的树种数据
			monitorTypeData: [], // 存储完整的监测类型数据
			levelData: [], // 存储完整的级别数据
			showYearPicker: false,
			showTreePicker: false,
			showTreeMultiPicker: false, // 自定义树种多选弹窗
			// showComparePicker: false, // 已移除，监测树种直接使用树种选择器
			showMonitorPicker: false,
			showLevelPicker: false,
			yearColumns: [
				[] // 动态生成年份数据
			],
			selectedYears: [], // 存储选中的年份
			// 环形图数据(默认显示) - 移除假数据
			ringData: {
				series: [{
					data: []
				}]
			},
			// 各年份-树种数据映射 - 移除假数据
			treeYearMap: {},
			// 环形图配置
			ringOpts: {
				type: 'ring',
				padding: [5, 5, 5, 5],
				legend: {
					show: true,
					position: 'bottom',
					lineHeight: 25
				},
				title: {
					name: '', // 置空中间主标题
					color: '#666666',
					fontSize: 0
				},
				subtitle: {
					name: '', // 副标题（默认显示百分比）
					fontSize: 0
				},
				series: [{
					center: ['50%', '50%'],
					radius: ['45%', '0%'], // 内半径45%，外半径75%，形成细环形
					labelLine: {
						show: false
					},
					label: {
						show: false
					}
				}]
			},
			// 树种选择器数据
			treeColumns: [
				[] // 动态填充树种数据
			],
			// 对比类型选择器数据（已移除，监测树种直接使用树种选择器）
			monitorColumns: [
				[] // 动态填充监测类型数据
			],
			levelColumns: [
				[] // 动态填充级别数据
			],
			// 合格率（柱状图）数据：按年份-城市 - 移除假数据
			passYearMap: {},
			// 柱状图配置
			columnOpts: {
				legend: {
					show: true
				},
				xAxis: {
					disabled: false,
					rotateLabel: true
				},
				yAxis: {
					data: [{
						format: '%.0f%'
					}]
				},
				extra: {
					column: {
						width: 22,
						seriesGap: 4,
						barBorderRadius: [6, 6, 0, 0]
					}
				}
			},
			chartData: [
				{ name: '市A', rate: 82.58 },
				{ name: '市B', rate: 70.40 },
				{ name: '市C', rate: 70.77 },
				{ name: '市D', rate: 94.15 },
				{ name: '市E', rate: 97.80 },
				{ name: '市F', rate: 74.76 },
				{ name: '市G', rate: 91.99 },
				{ name: '市H', rate: 85.00 }
			],
			// 多年份对比数据
			multiYearData: {
				'2015': [
					{ name: '市A', rate: 70.20 },
					{ name: '市B', rate: 65.30 },
					{ name: '市C', rate: 62.80 },
					{ name: '市D', rate: 85.90 },
					{ name: '市E', rate: 89.10 },
					{ name: '市F', rate: 67.20 },
					{ name: '市G', rate: 82.60 },
					{ name: '市H', rate: 75.40 }
				],
				'2016': [
					{ name: '市A', rate: 72.90 },
					{ name: '市B', rate: 66.80 },
					{ name: '市C', rate: 64.20 },
					{ name: '市D', rate: 87.20 },
					{ name: '市E', rate: 91.50 },
					{ name: '市F', rate: 69.10 },
					{ name: '市G', rate: 84.30 },
					{ name: '市H', rate: 77.20 }
				],
				'2017': [
					{ name: '市A', rate: 74.30 },
					{ name: '市B', rate: 67.10 },
					{ name: '市C', rate: 65.50 },
					{ name: '市D', rate: 88.80 },
					{ name: '市E', rate: 93.20 },
					{ name: '市F', rate: 70.40 },
					{ name: '市G', rate: 86.10 },
					{ name: '市H', rate: 79.60 }
				],
				'2018': [
					{ name: '市A', rate: 75.40 },
					{ name: '市B', rate: 68.30 },
					{ name: '市C', rate: 66.20 },
					{ name: '市D', rate: 90.00 },
					{ name: '市E', rate: 94.10 },
					{ name: '市F', rate: 71.20 },
					{ name: '市G', rate: 87.30 },
					{ name: '市H', rate: 80.80 }
				],
				'2019': [
					{ name: '市A', rate: 76.58 },
					{ name: '市B', rate: 69.40 },
					{ name: '市C', rate: 67.77 },
					{ name: '市D', rate: 91.15 },
					{ name: '市E', rate: 95.80 },
					{ name: '市F', rate: 72.76 },
					{ name: '市G', rate: 88.99 },
					{ name: '市H', rate: 82.00 }
				],
				'2020': [
					{ name: '市A', rate: 75.20 },
					{ name: '市B', rate: 68.30 },
					{ name: '市C', rate: 65.80 },
					{ name: '市D', rate: 88.90 },
					{ name: '市E', rate: 92.10 },
					{ name: '市F', rate: 70.20 },
					{ name: '市G', rate: 85.60 },
					{ name: '市H', rate: 78.40 }
				],
				'2021': [
					{ name: '市A', rate: 78.90 },
					{ name: '市B', rate: 69.80 },
					{ name: '市C', rate: 68.20 },
					{ name: '市D', rate: 91.20 },
					{ name: '市E', rate: 94.50 },
					{ name: '市F', rate: 72.10 },
					{ name: '市G', rate: 88.30 },
					{ name: '市H', rate: 81.20 }
				],
				'2022': [
					{ name: '市A', rate: 80.30 },
					{ name: '市B', rate: 70.10 },
					{ name: '市C', rate: 69.50 },
					{ name: '市D', rate: 80.80 },
					{ name: '市E', rate: 96.20 },
					{ name: '市F', rate: 73.40 },
					{ name: '市G', rate: 90.10 },
					{ name: '市H', rate: 83.60 }
				],
				'2023': [
					{ name: '市A', rate: 81.40 },
					{ name: '市B', rate: 70.30 },
					{ name: '市C', rate: 70.20 },
					{ name: '市D', rate: 100.00 },
					{ name: '市E', rate: 97.10 },
					{ name: '市F', rate: 74.20 },
					{ name: '市G', rate: 91.30 },
					{ name: '市H', rate: 84.80 }
				],
				'2024': [
					{ name: '市A', rate: 82.58 },
					{ name: '市B', rate: 70.40 },
					{ name: '市C', rate: 70.77 },
					{ name: '市D', rate: 94.15 },
					{ name: '市E', rate: 97.80 },
					{ name: '市F', rate: 74.76 },
					{ name: '市G', rate: 91.99 },
					{ name: '市H', rate: 85.00 }
				]
			},
			// 抽检合格率分析柱状图配置
			columnOpts: {
				type: 'column',
				padding: [10, 10, 10, 10],
				legend: {
					show: true,
					position: 'right',
					lineHeight: 25
				},
				title: {
					name: '', // 置空中间主标题
					color: '#666666',
					fontSize: 0
				},
				subtitle: {
					name: '', // 副标题（默认显示百分比）
					fontSize: 0
				},
				series: [{
					barWidth: 30, // 柱状图宽度
					barRadius: 5, // 柱状图圆角
					barGap: '50%', // 柱状图间距
					barCategoryGap: '30%', // 柱状图类别间距
					label: {
						show: true,
						position: 'top',
						color: '#333',
						fontSize: 24,
						formatter: '{c}%'
					},
					itemStyle: {
						color: '#0A993B' // 柱状图颜色
					}
				}]
			}
		}
	},
	onLoad() {
		this.generateYearOptions();
		this.getTreeSpeciesList();
		// this.getTreeSpeciesData(); // 移除自动调用，改为用户点击查询时调用
		this.getTypeData();
		this.getLevelData();
	},
	methods: {
		// 获取树种列表
		getTreeSpeciesList() {
			getTreeSpeciesList().then(res => {
				console.log('树种列表数据:', res);
				if (res && res.length > 0) {
					// 保存完整的树种数据
					this.treeSpeciesData = res;
					// 提取树种标签并更新treeColumns
					this.treeColumns = [res.map(item => item.label)];
					console.log('更新后的树种选项:', this.treeColumns);
				}
			}).catch(err => {
				console.error('获取树种列表失败:', err);
				// 如果API失败，使用默认数据
				this.treeColumns = [['苹果', '梨', '桃', '葡萄', '樱桃']];
			})
		},
		// 生成年份选项
		generateYearOptions() {
			const currentYear = new Date().getFullYear();
			const startYear = currentYear - 30; // 当前年份往前30年
			const years = [];
			
			// 生成从当前年份往前50年到当前年份的所有年份（降序）
			for (let year = currentYear; year >= startYear; year--) {
				years.push(year.toString());
			}
			
			this.yearColumns = [years];
			console.log('生成的年份选项:', this.yearColumns);
			console.log('年份范围:', `${startYear} - ${currentYear} (共${years.length}年)`);
			console.log('当前年份位置:', years.indexOf(currentYear.toString()));
		},
		// 获取监测类型数据
		getTypeData() {
			typeShujufenxi().then(res => {
				console.log('监测类型数据:', res);
				if (res.code === 200 && res.data && res.data.length > 0) {
					// 保存完整的监测类型数据
					this.monitorTypeData = res.data;
					// 提取监测类型标签并更新monitorColumns
					this.monitorColumns = [res.data.map(item => item.dictLabel)];
					console.log('更新后的监测类型选项:', this.monitorColumns);
				}
			}).catch(err => {
				console.error('获取监测类型数据失败:', err);
				// 如果API失败，使用默认数据
				this.monitorColumns = [['常规监测', '专项监测', '应急监测']];
			})
		},
		// 获取监测级别数据
		getLevelData() {
			levelShujufenxi().then(res => {
				console.log('级别数据:', res);
				if (res.code === 200 && res.data && res.data.length > 0) {
					// 保存完整的级别数据
					this.levelData = res.data;
					// 提取级别标签并更新levelColumns
					this.levelColumns = [res.data.map(item => item.dictLabel)];
					console.log('更新后的级别选项:', this.levelColumns);
				}
			}).catch(err => {
				console.error('获取级别数据失败:', err);
				// 如果API失败，使用默认数据
				this.levelColumns = [['省级', '市级', '县级']];
			})
		},
		// 获取各树种抽检比例数据
		getTreeSpeciesData() {
			// 根据标签找到对应的代码值（仅用于监测类型和级别）
			const getMonitorTypeCode = (label) => {
				const item = this.monitorTypeData.find(item => item.dictLabel === label);
				return item ? item.dictValue : '';
			};
			
			const getLevelCode = (label) => {
				const item = this.levelData.find(item => item.dictLabel === label);
				return item ? item.dictValue : '';
			};
			
			// 构建API参数 - product传递文字，支持多选
			const params = {
				product: this.filterData.treeType && this.filterData.treeType.length > 0 
					? this.filterData.treeType.join('，') 
					: '', // 树种文字，多个用中文逗号分隔
				year: this.selectedYears && this.selectedYears.length > 0 
					? this.selectedYears[0]  // 只传第一个选中的年份
					: '', // 如果没有选择年份，传空字符串
				detectionType: this.filterData.monitorType ? getMonitorTypeCode(this.filterData.monitorType) : '', // 监测类型代码
				detectionLevel: this.filterData.level ? getLevelCode(this.filterData.level) : '' // 监测级别代码
			};
			
			console.log('调用getTreeSpecies API参数:', params);
			
			getTreeSpecies(params).then(res => {
				console.log('树种抽检比例数据:', res);
				// 处理返回的数据，更新图表
				if (res && res.data) {
					this.updateChartWithApiData(res.data);
				} else {
					// 如果API返回成功但没有data字段，说明是空数据
					console.log('API返回成功但无数据，清空图表');
					this.updateChartWithApiData([]);
				}
			}).catch(err => {
				console.error('获取树种抽检比例数据失败:', err);
				uni.showToast({
					title: '数据获取失败',
					icon: 'error'
				});
			})
		},
		// 使用API数据更新图表
		updateChartWithApiData(apiData) {
			console.log('使用API数据更新图表:', apiData);
			
			// 处理API返回的树种数据格式: [{枣（不含冬枣）: 206}, {花椒: 45}, {板栗: 238}, {核桃: 116}]
			if (Array.isArray(apiData) && apiData.length > 0) {
				// 将API数据转换为环形图需要的格式
				const chartData = apiData.map(item => {
					// 获取对象的键值对
					const entries = Object.entries(item);
					if (entries.length > 0) {
						const [name, value] = entries[0];
						return {
							name: name,
							value: value
						};
					}
					return null;
				}).filter(item => item !== null);
				
				// 更新环形图数据
				this.ringData = {
					series: [{
						data: chartData
					}]
				};
				
				console.log('更新后的环形图数据:', this.ringData);
				
				// 强制更新视图
				this.$forceUpdate();
				
				// 切换到环形图标签页
				this.currentTab = 1;
			} else {
				// 如果API返回空数据，清空环形图数据
				console.log('API返回空数据，清空环形图');
				this.ringData = {
					series: [{
						data: []
					}]
				};
				
				// 强制更新视图
				this.$forceUpdate();
				
				// 切换到环形图标签页
				this.currentTab = 1;
			}
		},
		// 切换标签页
		switchTab(index) {
			this.currentTab = index;
			// 根据标签页切换数据
			this.loadDataByTab(index);
		},

		// 获取选中年份的文本显示
		getSelectedYearsText() {
			if (!this.selectedYears || this.selectedYears.length === 0) {
				return '';
			}
			return this.selectedYears.join('、');
		},

		// 获取选中树种的文本显示
		getSelectedTreeTypesText() {
			if (!this.filterData.treeType || this.filterData.treeType.length === 0) {
				return '';
			}
			return this.filterData.treeType.join('、');
		},

		// 获取所有城市多年份数据
		getAllCitiesData() {
			const cities = ['市A', '市B', '市C', '市D', '市E', '市F', '市G', '市H'];
			const result = [];

			// 如果没有选择年份，显示默认年份数据
			const yearsToShow = this.selectedYears && this.selectedYears.length > 0
				? this.selectedYears
				: ['2024'];

			console.log('要显示的年份:', yearsToShow);

			cities.forEach(cityName => {
				const cityData = {
					name: cityName,
					years: []
				};

				yearsToShow.forEach(year => {
					let yearData = this.multiYearData[year];
					
					// 如果没有预设数据，生成模拟数据
					if (!yearData) {
						const yearNum = parseInt(year);
						const currentYear = new Date().getFullYear();
						const yearsDiff = yearNum - currentYear;
						
						// 根据年份差异生成城市数据
						const baseRate = 75 + yearsDiff * 0.3;
						yearData = cities.map(city => ({
							name: city,
							rate: Math.max(50, Math.min(100, baseRate + (Math.random() - 0.5) * 20))
						}));
					}
					
					if (yearData) {
						const cityYearData = yearData.find(item => item.name === cityName);
						if (cityYearData) {
							cityData.years.push({
								year: year,
								rate: cityYearData.rate
							});
						}
					}
				});

				result.push(cityData);
			});

			console.log('生成的城市数据:', result);
			return result;
		},

		// 年份选择确认（单选模式）
		yearConfirm(e) {
			console.log('年份选择结果:', e.value);
			// 获取选中的年份
			const selectedYear = e.value[0];

			// 单选模式：直接替换选中的年份
			this.selectedYears = [selectedYear];
			this.filterData.years = [selectedYear];
			this.showYearPicker = false;
			console.log('选中的年份:', this.selectedYears);
		},

		// 树种选择确认（支持多选）
		treeConfirm(e) {
			console.log('树种选择结果:', e.value);
			// 单选模式下，e.value[0] 是选中的值
			this.filterData.treeType = [e.value[0]];
			this.showTreePicker = false;
			console.log('选择的树种:', this.filterData.treeType);
		},

		// 切换树种选择状态
		toggleTreeSelect(tree) {
			const index = this.filterData.treeType.indexOf(tree);
			if (index > -1) {
				this.filterData.treeType.splice(index, 1);
			} else {
				this.filterData.treeType.push(tree);
			}
			console.log('当前选择的树种:', this.filterData.treeType);
		},

		// 确认树种多选
		confirmTreeMultiSelect() {
			this.showTreeMultiPicker = false;
			console.log('最终选择的树种:', this.filterData.treeType);
		},

		// 监测类型选择确认
		monitorConfirm(e) {
			const selectedLabel = e.value[0];
			this.filterData.monitorType = selectedLabel;
			this.showMonitorPicker = false;
			console.log('选择的监测类型:', selectedLabel);
		},

		// 级别选择确认
		levelConfirm(e) {
			const selectedLabel = e.value[0];
			this.filterData.level = selectedLabel;
			this.showLevelPicker = false;
			console.log('选择的级别:', selectedLabel);
		},

		// 查询数据
		queryData() {
			console.log('查询条件:', this.filterData);
			console.log('选中年份:', this.selectedYears);
			
			// 调用API获取数据
			this.getTreeSpeciesData();
			
			uni.showToast({
				title: '查询成功',
				icon: 'success'
			});
		},

		// 更新图表数据
		updateChartData() {
			// 这个方法现在不需要了，因为我们直接使用 getAllCitiesData() 方法
			// 数据会实时根据 selectedYears 更新
		},

		// 重置筛选条件
		resetFilter() {
			this.filterData = {
				years: [],
				treeType: [], // 改为数组
				monitorType: '',
				level: ''
			};
			this.selectedYears = [];
			// 不需要调用 updateChartData，因为 getAllCitiesData() 会实时响应 selectedYears 的变化
		},

		// 根据标签页加载数据
		loadDataByTab(tabIndex) {
			// 这里可以根据不同的标签页加载不同的数据
			console.log('切换到标签页:', tabIndex);
		},
		// 获取需要显示的年份（若未选择，默认显示当前年）
		getYearsToShow() {
			if (this.selectedYears && this.selectedYears.length > 0) {
				return this.selectedYears;
			}
			return [new Date().getFullYear().toString()]; // 默认显示当前年份
		},

		// 打开年份选择器
		openYearPicker() {
			this.showYearPicker = true;
		},

		// 获取当前年份默认值
		getCurrentYearDefault() {
			return [new Date().getFullYear().toString()];
		},
		// 根据年份生成环形图数据
		getRingDataByYear(year) {
			// 优先使用API返回的数据
			if (this.ringData && this.ringData.series && this.ringData.series[0] && this.ringData.series[0].data.length > 0) {
				return this.ringData;
			}
			
			// 其次使用预设数据
			if (this.treeYearMap[year]) {
				return { series: [{ data: this.treeYearMap[year] }] };
			}
			
			// 如果没有数据，返回空数据
			return { series: [{ data: [] }] };
		},

		// 判断是否有环形图数据
		hasRingData() {
			// 只检查API返回的数据，不检查预设数据
			if (this.ringData && this.ringData.series && this.ringData.series[0] && this.ringData.series[0].data.length > 0) {
				return true;
			}
			
			return false;
		},

		// 树种选择确认
		treeConfirm(e) {
			const selectedLabel = e.value[0];
			this.filterData.treeType = selectedLabel;
			this.showTreePicker = false;
			console.log('选择的树种:', selectedLabel);
		},
		// 生成合格率柱状图数据
		getPassRateChartData() {
			let years = [];
			if (this.selectedYears && this.selectedYears.length > 0) {
				years = this.selectedYears;
			} else {
				years = ['2023', '2024'];
			}
			
			const categories = ['甲', '乙', '丙'];
			const series = [];
			
			years.forEach((year) => {
				let yearData;
				
				// 优先使用预设数据
				if (this.passYearMap[year]) {
					yearData = this.passYearMap[year];
				} else {
					// 生成模拟数据
					const yearNum = parseInt(year);
					const currentYear = new Date().getFullYear();
					const yearsDiff = yearNum - currentYear;
					
					// 根据年份差异生成合格率数据
					const baseRate = 85 + yearsDiff * 0.5; // 基础合格率
					yearData = {
						categories: categories,
						series: [{
							name: '合格率(%)',
							data: [
								Math.max(60, Math.min(100, baseRate + 10)), // 甲级
								Math.max(50, Math.min(95, baseRate)), // 乙级
								Math.max(40, Math.min(90, baseRate - 10)) // 丙级
							]
						}]
					};
				}
				
				if (yearData && yearData.series && yearData.series[0] && Array.isArray(yearData.series[0].data)) {
					series.push({ name: year, data: yearData.series[0].data.slice(0, categories.length) });
				}
			});
			
			// 如果没有数据，使用默认数据
			if (series.length === 0) {
				const fallbackYear = '2024';
				const ydata = this.passYearMap[fallbackYear];
				return { categories: ydata.categories, series: [{ name: fallbackYear, data: ydata.series[0].data }] };
			}
			
			return { categories, series };
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;

	z-index: 1;
}

.tab-container {
	display: flex;
	background: #fff;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 10rpx 0;
		font-size: 28rpx;
		color: #666;
		position: relative;

		&.active {
			color: #0A993B;
			font-weight: bold;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 4rpx;
				background: #0A993B;
				border-radius: 2rpx;
			}
		}
	}
}

.filter-container {
	background: #fff;
	margin: 20rpx;
	padding: 30rpx;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

	.filter-row {
		display: flex;
		margin-bottom: 20rpx;

		.filter-item {
			flex: 1;
			margin-right: 20rpx;

			&:last-child {
				margin-right: 0;
			}

			.label {
				display: block;
				font-size: 26rpx;
				color: #333;
				margin-bottom: 10rpx;
			}

			.input-wrapper {
				position: relative;
				display: flex;
				align-items: center;
				background: #f8f9fa;
				border-radius: 8rpx;
				padding: 10rpx;

				.input {
					flex: 1;
					font-size: 28rpx;
					color: #333;
					background: transparent;
					border: none;

					&::placeholder {
						color: #999;
					}
				}
			}
		}
	}

	.filter-buttons {
		display: flex;
		gap: 20rpx;

		.btn {
			flex: 1;
			padding: 0;
			border-radius: 8rpx;
			font-size: 28rpx;
			border: none;

			&.btn-query {
				background: #fff;
				color: #0A993B;
				border: 2rpx solid #0A993B;
			}

			&.btn-reset {
				background: #999;
				color: #fff;
			}
		}
	}
}

.chart-container {
	background: #fff;
	margin: 20rpx;
	padding: 30rpx 0;
	border-radius: 16rpx;

	.chart-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		text-align: center;

		.year-info {
			font-size: 24rpx;
			color: #666;
			font-weight: normal;
			margin-left: 10rpx;
		}
	}

	.chart-wrapper {
		.city-group {
			margin-bottom: 40rpx;
			padding: 0 20rpx;

			.year-bars {
				.year-bar-item {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;

					.year-label {
						font-size: 24rpx;
						color: #666;
						text-align: right;
						margin-right: 20rpx;
					}

					.chart-bar {
						height: 35rpx;
						background: #f0f0f0;
						border-radius: 17rpx;
						overflow: hidden;
						position: relative;
						margin-right: 80rpx;
						width: 100%;

						.bar-fill {
							height: 100%;
							border-radius: 17rpx;
							transition: width 0.3s ease;

							&.bar-1 {
								background: linear-gradient(90deg, #0A993B, #3ecf5e);
							}

							&.bar-2 {
								background: linear-gradient(90deg, #18a058, #4cd27a);
							}

							&.bar-3 {
								background: linear-gradient(90deg, #2bbb66, #63d68c);
							}

							&.bar-4 {
								background: linear-gradient(90deg, #24a36b, #5ed394);
							}

							&.bar-5 {
								background: linear-gradient(90deg, #1c7f5a, #3fbf82);
							}
						}
					}

					.chart-value {
						position: absolute;
						right: 30rpx;
						font-size: 22rpx;
						color: #666;
						font-weight: bold;
						width: 80rpx;
						text-align: right;
					}
				}
			}
		}
	}

	// 环形图容器样式
	.chart-wrapper {
		&:has(qiun-data-charts) {
			padding: 20rpx;
			min-height: 600rpx;
		}
	}

	// 无数据提示样式
	.no-data-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 40rpx;
		min-height: 400rpx;

		.no-data-icon {
			font-size: 120rpx;
			margin-bottom: 30rpx;
			opacity: 0.3;
		}

		.no-data-text {
			font-size: 32rpx;
			color: #999;
			margin-bottom: 20rpx;
			font-weight: bold;
		}

		.no-data-tip {
			font-size: 26rpx;
			color: #ccc;
			text-align: center;
			line-height: 1.5;
		}
	}
}

// 自定义树种多选弹窗样式
.tree-multi-picker {
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;
	max-height: 80vh;

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 40rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.picker-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.picker-confirm {
			font-size: 28rpx;
			color: #0A993B;
			font-weight: bold;
		}
	}

	.picker-content {
		padding: 20rpx 0;
		max-height: 60vh;
		overflow-y: auto;

		.tree-item {
			display: flex;
			align-items: center;
			padding: 20rpx 40rpx;
			border-bottom: 1rpx solid #f8f8f8;

			&:last-child {
				border-bottom: none;
			}

			.tree-checkbox {
				width: 40rpx;
				height: 40rpx;
				border: 2rpx solid #ddd;
				border-radius: 8rpx;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;

				&.active {
					background: #0A993B;
					border-color: #0A993B;
				}
			}

			.tree-label {
				font-size: 28rpx;
				color: #333;
				flex: 1;
			}
		}
	}
}
</style>
